package com.lhj.xxsc.coupon.service.impl;

import com.lhj.xxsc.coupon.entity.SeckillSkuRelationEntity;
import com.lhj.xxsc.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxsc.common.utils.PageUtils;
import com.xxsc.common.utils.Query;

import com.lhj.xxsc.coupon.dao.SeckillSessionDao;
import com.lhj.xxsc.coupon.entity.SeckillSessionEntity;
import com.lhj.xxsc.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
	@Autowired
	SeckillSkuRelationService seckillSkuRelationService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<SeckillSessionEntity> page = this.page(
				new Query<SeckillSessionEntity>().getPage(params),
				new QueryWrapper<SeckillSessionEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public List<SeckillSessionEntity> getLates3DaySession() {
		List<SeckillSessionEntity> seckillSessionEntityList = new ArrayList<>();
		LocalDate now = LocalDate.now();
		List<SeckillSessionEntity> list = this.list(new QueryWrapper<SeckillSessionEntity>().between("start_time", startTime(), endTime()));
		if (!CollectionUtils.isEmpty(list)) {
			seckillSessionEntityList = list.stream().map(item -> {
				Long id = item.getId();
				List<SeckillSkuRelationEntity> relationEntities = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));
				item.setRelationSkus(relationEntities);
				return item;
			}).collect(Collectors.toList());
		}
		return seckillSessionEntityList;
	}

	// 第一天最小时间00:00:00
	private String startTime() {
		LocalDateTime start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
		String startTime = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		return startTime;
	}

	// 第三天最大限度59:59:59
	private String endTime() {
		LocalDateTime end = LocalDateTime.of(LocalDate.now().plusDays(2), LocalTime.MAX);
		String endTime = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		return endTime;
	}

}
